<!--
   Copyright 2024 The Google Research Authors.
  
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
  
       http://www.apache.org/licenses/LICENSE-2.0
  
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<!DOCTYPE html>
<html>
<head>
<title>Click Option Multi Layouts Click Widgt Login User Popup Task</title>
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="../core/core.css">
<style>
  #form2 .widget { margin: 5px 0;}
  #form2 textarea { height: 20px; }
  #form2 input[type=input] { width: 120px !important; }
  .bold { font-weight: bold; }
  #popup {
    position: absolute;
    top: 62px; left: 8px;
    width: 120px; height: 120px;
    border: 2px solid #888;
    background-color: #EEE;
    padding: 5px 10px; font-size: 12px;
    display: flex; flex-direction: column; justify-content: space-around;
  }
  #popup p {
    margin: 0; text-align: center;
  }
  .hide { display: none; }
  /* 160 + 160 + 50 + 30 */
  #wrap,
  #sync-task-cover {
    height: 400px;
    width: 160px;
  }

  #click-canvas,
  #reward-display {
    left: 165px;
  }

  #query {
    background-color: #FF0;
    font-size: 10px;
    height: 74px;
    padding: 3px;
  }
  input[id="password"] { width: 120px; }
  input[id="username"] { width: 120px; }
</style>

<!-- JS -->
<script src="../core/core.js"></script>
<script src="../core/d3.v3.min.js"></script>
<script src="../common/ui_utils.js"></script>
<script src="../core/jquery-ui/external/jquery/jquery.js"></script>

<script>
core.EPISODE_MAX_TIME = 2000000;  // 2000 seconds

var ELEMENT_NAMES = ['radio', 'checkbox', 'text', 'textarea', 'button'];
var ELEMENT_HTML = {
  'radio': {'start': '<div class="widget"><label><input type="radio" data-type="radio" name="radio">',
    'end': '</label></div>'},
  'checkbox': {'start':' <div class="widget"><label><input type="checkbox" data-type="checkbox">',
    'end':'</label></div>'},
  'text': {'start': '<div class="widget"><input type="input" data-type="text" value="',
    'end':'"></div>'},
  'textarea': {'start':'<div class="widget"><textarea data-type="textarea">',
    'end':'</textarea></div>'},
  'button': {'start': '<div class="widget"><button data-type="button">',
    'end':'</button></div>'}
};
var NUM_ELEMENTS = 5;
var GENRES = ['Action', 'Adventure', 'Comedy', 'Crime', 'Drama', 'Fantasy', 'Historical', 'Horror', 'Mystery', 'Paranoid', 'Political', 'Romance', 'Saga', 'Satire', 'Surreal', 'Thriller', 'Urban', 'Western'];

var createWidgets = function(){
  // generate query text in the UI
  var elements = [];
  var elements_html = [];
  for(var i=0;i<NUM_ELEMENTS;i++){
    randIndex = core.randi(0,ELEMENT_NAMES.length);
    var elemName = ELEMENT_NAMES[randIndex];
    var randomText = ui_utils.generateString(1,6);
    elements_html.push(ELEMENT_HTML[elemName]['start'] + randomText + ELEMENT_HTML[elemName]['end']);
    elements.push(elemName);
  }

  return [elements, elements_html.join(' ')];
}

var GENRES = ['Action', 'Adventure', 'Comedy', 'Crime', 'Drama', 'Fantasy', 'Historical', 'Horror', 'Mystery', 'Paranoid', 'Political', 'Romance', 'Saga', 'Satire', 'Surreal', 'Thriller', 'Urban', 'Western'];

var layout1 = function (checker) {
  var genreBox = $('<input type=text>');
  var nameBox = $('<input type=text>');
  var yearBox = $('<input type=text>');
  var rows = [
    $('<p>').append('<span>Genre:</span>').append(genreBox),
    $('<p>').append('<span>Director:</span>').append(nameBox),
    $('<p>').append('<span>Year:</span>').append(yearBox),
    ];
  core.shuffle(rows);
  rows.forEach(function (row) { row.appendTo('#form1'); });
  var submit = $('<button type=button>').text('Submit').appendTo('#form1')
    .click(function () {
      checker(genreBox.val(), nameBox.val(), yearBox.val());
    });
  $('#form1').append(layout1Style);
}

var layout1Style = `<style>
#form1 span { width: 50px; display: inline-block; margin-left: 10px;}
#form1 input[type=text] { width: 80px; }
</style>`;

var layout2 = function (checker) {
  var genreBox = $('<input type=text>');
  var nameBox = $('<input type=text>');
  var yearBox = $('<input type=text>');
  var rows = [
    $('<div class=row>').append('<div>Genre</div>').append(genreBox),
    $('<div class=row>').append('<div>Director Name</div>').append(nameBox),
    $('<div class=row>').append('<div>Year</div>').append(yearBox),
    ];
  core.shuffle(rows);
  rows.forEach(function (row) { row.appendTo('#form1'); });
  var submit = $('<button type=button>').text('Search')
    .appendTo($('<div class=submit-row>').appendTo('#form1'))
    .click(function () {
      checker(genreBox.val(), nameBox.val(), yearBox.val());
    });
  $('#form1').append(layout2Style);
}

var layout2Style = `<style>
#form1 div.row { margin: 5px; }
#form1 div.row div { font-weight: bold; }
#form1 div.row input[type=text] { width: 140px; }
#form1 div.submit-row { text-align: center; }
</style>`;

var layout3 = function (checker) {
  var genreBox = $('<input type=text>');
  var nameBox = $('<input type=text>');
  var yearBox = $('<input type=text>');
  var rows = [
    $('<tr>').append('<th>Genre</th>').append($('<td>').append(genreBox)),
    $('<tr>').append('<th>Director</th>').append($('<td>').append(nameBox)),
    $('<tr>').append('<th>Year</th>').append($('<td>').append(yearBox)),
    ];
  core.shuffle(rows);
  $('<div class=title-div>Movie Search</div>').appendTo('#form1');
  var table = $('<table>').appendTo('#form1');
  rows.forEach(function (row) { row.appendTo(table); });
  var submit = $('<div class=final>').text('Submit').appendTo('#form1')
    .click(function () {
      checker(genreBox.val(), nameBox.val(), yearBox.val());
    });
  $('#form1').append(layout3Style);
}

var layout3Style = `<style>
#form1 div.title-div { text-align: center; font-weight: bold; margin-top: 10px; font-size: 120%; }
#form1 table { margin: 5px auto; }
#form1 th { text-align: right; }
#form1 input[type=text] { width: 90px; }
#form1 .final { padding: 2px; border: 1px solid gray; margin: 2px auto; width: 50px; text-align: center; background: #fed; cursor: pointer; }
#form1 .final:hover { background: #fcc; }
</style>`;

var layout4 = function (checker) {
  var genreBox = $('<input type=text>');
  var nameBox = $('<input type=text>');
  var yearBox = $('<input type=text>');
  var rows = [
    $('<div class=field>').append('<div class=label>Movie Genre</div>').append($('<div class=input>').append(genreBox)),
    $('<div class=field>').append('<div class=label>Director Name</div>').append($('<div class=input>').append(nameBox)),
    $('<div class=field>').append('<div class=label>Released Date</div>').append($('<div class=input>').append(yearBox)),
    ];
  core.shuffle(rows);
  rows.forEach(function (row) { row.appendTo('#form1'); });
  var submit = $('<button type=button>').text('Go!')
    .appendTo($('<div class=submit-row>').appendTo('#form1'))
    .click(function () {
      checker(genreBox.val(), nameBox.val(), yearBox.val());
    });
  $('#form1').append(layout4Style);
}

var layout4Style = `<style>
#form1 div.field { background-color: #DDD; margin: 2px; padding: 3px 8px; border-radius: 3px;}
#form1 input[type=text] { width: 98%; }
#form1 .submit-row { text-align: center; }
</style>`;

var layout5 = function (checker) {
  var genreBox = $('<input type=text>');
  var nameBox = $('<input type=text>');
  var yearBox = $('<input type=text>');
  var rows = [
    $('<div class=ui-entry>').append(genreBox).append('<div class=ui-label>Genre</div>'),
    $('<div class=ui-entry>').append(nameBox).append('<div class=ui-label>Director</div>'),
    $('<div class=ui-entry>').append(yearBox).append('<div class=ui-label>Year</div>'),
    ];
  core.shuffle(rows);
  var wrapper = $('<div class=ui-entry-wrap>').appendTo('#form1');
  rows.forEach(function (row) { row.appendTo(wrapper); });
  var submitRow = $('<div class=ui-footer>').appendTo('#form1');
  var submit = $('<div class=ui-submit>').text('Search').appendTo(submitRow)
    .click(function () {
      checker(genreBox.val(), nameBox.val(), yearBox.val());
    });
  $('#form1').append(layout5Style);
}

var layout5Style = `<style>
#form1 .ui-entry-wrap { width: 140px; margin: 3px auto; padding: 2px 5px; background-color: #333; border-radius: 5px;}
#form1 .ui-entry { margin: 8px auto; }
#form1 .ui-entry input[type=text] { padding: 0; margin: 0; width: 95%; }
#form1 .ui-label { font-weight: bold; color: white; }
#form1 .ui-footer { margin: 0 auto; text-align: center; }
#form1 .ui-submit { display: inline-block; border: 1px solid gray; background-color: #BBB; border-radius: 3px; padding: 3px; width: 50px; text-align: center; box-shadow: inset 0px 1px 0px 0px #EEE; cursor: pointer; }
#form1 .ui-submit:active { box-shadow: inset 0px 1px 0px 0px #999; }
</style>`;

var layouts = [layout1, layout2, layout3, layout4, layout5];


var createElements = function(div){
  var n = core.randi(2, 7);
  var clickNames = [];
  for(var i=0;i<n;i++) {
    var chname = ui_utils.generateString(2,8);
    var label = div.append('label')
    label.append('input').attr('type', 'radio').attr('id', 'ch'+i).attr('name', 'radio');
    label[0][0].innerHTML += chname;
    div.append('br');
    clickNames.push(chname);
  }
  var ix = core.randi(0, n);
  var qstr = clickNames[ix];
  return {query: qstr, index: ix};
}


var genProblem = function() {
  var option_state = -1.0;
  var widget_state = -1.0;
  var div = d3.select('#area');
  div.html('');  // clear previous problem, if any

  div.append('div').attr('id', 'form1');
  div.append('div').attr('id', 'form2');
  $('#form2').addClass('hide');

  // click-option
  var form1Div = d3.select('#form1');
  form1Div.append('div').attr('id', 'boxes');
  var div_option = d3.select('#boxes');
  div_option.html('');
  var correctElement = createElements(div_option);

  // multi-layouts
  var eGenre = core.sample(GENRES).toLowerCase();
  var eName = core.sample(ui_utils.LAST_NAMES);
  var eYear = core.randi(1970, 2018);
  var checker = function (cGenre, cName, cYear) {
    option_state = d3.select('#ch'+correctElement.index)[0][0].checked ? 1.0 : -1.0;
    console.log('click-option', option_state);
    if (cGenre.toLowerCase().trim() == eGenre &&
        cName.toLowerCase().trim() == eName.toLowerCase() &&
        ('' + cYear) == ('' + eYear) && option_state == 1.0) {
      option_state = 1.0;
      console.log('multi-layouts', option_state);
    } else {
      option_state = -1.0;
      console.log('multi-layouts', option_state);
      core.endEpisode(option_state);
    }
    $('#form2').removeClass('hide');
    $('#form1').addClass('hide');
    console.log(d3.select('#form2 .widget'));
    $('#form2 .widget').on('click', function(){
      console.log('click-widget clicked');
      var elemType = $(this).find('input, textarea, button')[0].getAttribute('data-type');
      widget_state = elemType === chosenElement ? 1.0 : -1.0;
      console.log('click-widget', elemType, chosenElement, widget_state);
    });
  };

  // click-widget
  var elements = createWidgets();
  var chosenElement = core.sample(elements[0]);

  console.log(d3.select('#form2 .widget'));

  // login-user
  var form2Div = d3.select('#form2');
  form2Div.html(elements[1] + '<br><p><label class="bold">Username</label><input type="text" id="username"></p><p><label class="bold">Password</label><input type="password" id="password"></p><button id="subbtn" class="secondary-action">Login</button>');
  d3.select('#username')[0][0].value ='';
  d3.select('#password')[0][0].value ='';

  var user = core.sample(ui_utils.FIFTY_NAMES).toLowerCase();
  var password = ui_utils.generateString(2,6)

  // reward awarder
  d3.select('#subbtn').on('click', function(){
    var u = d3.select('#username')[0][0].value;
    var p = d3.select('#password')[0][0].value;
    login_state = (u === user && p === password) ? 1.0 : -1.0;
    if (widget_state == 1.0) {
      console.log('login-user', widget_state);
      core.endEpisode(login_state, true);
    } else {
      console.log('login-user', -1.0);
      core.endEpisode(-1, true);
    }
  });


  // instruction
  d3.select('#query').html('Select ' + correctElement.query + ', search for <b>' + eGenre + '</b> movies directed by <b>' + eName + '</b> from year <b>' + eYear + '</b>, click on a "' + chosenElement + '" widget, and then enter the <span class="bold">username</span> "' + user + '" and the <span class="bold">password</span> "' + password + '" into the text fields and press login.');
  // d3.select('#query').html('Click on a "' + chosenElement + '" widget, and enter the <span class="bold">username</span> "' + user + '" and the <span class="bold">password</span> "' + password + '" into the text fields and press login, after selecting ' + correctElement.query + ', and searching for <b>' + eGenre + '</b> movies directed by <b>' + eName + '</b> from year <b>' + eYear + '</b>.');

  var layout = core.sample(layouts);
  layout(checker);

  // Clean the previous states
  d3.selectAll('#username, #password, #subbtn').attr('disabled', null);
  d3.select('#popup').remove();
  var popupShown = false;

  // Random Popup 
  function showPopup () {
    if (popupShown) return;
    d3.selectAll('#username, #password, #subbtn').attr('disabled', 'disabled');
    var message
    if (Math.random() < 0.85) {
      message = 'Your session is ' + core.sample([
          'about to expire.',
          'about to time out.',
          'expiring soon.',
          'soon to expire.',
          'timing out soon.',
          'going to expire soon.',
          'going to time out soon.',
          ]);
    } else {
      message = core.sample([
        'You are running out of time, aren\'t you?',
        'You have 10 new messages.',
        'Your mother is calling you for dinner.',
        'Please do not panic.',
        'This is an annoying popup message.',
        'It looks like you are trying to log in.',
        'You look good today.',
        'Sorry for this annoying message.',
        ]);
    }
    d3.select('#area').append('div').attr('id', 'popup').html(`
        <p>` + message + `</p>
        <p>Exit to home page?</p>
        <p><button id=popup-ok>OK</button> <button id=popup-cancel>Cancel</button>`);
    d3.select('#popup-ok').on('click', function () {
      core.endEpisode(-1);
    });
    d3.select('#popup-cancel').on('click', function () {
      d3.selectAll('#username, #password, #subbtn').attr('disabled', null);
      d3.select('#popup').remove();
    });
    popupShown = true;
  }
  var popupMode = core.sample([
      'username', 'password', null, null,
      ]);
  d3.select('#username').on('focus', popupMode != 'username' ? null : showPopup);
  d3.select('#password').on('focus', popupMode != 'password' ? null : showPopup);
}

window.onload = function() {
  core.startEpisode();
}
</script>
</head>
<!-- Base HTML -->
<body>
<div id="wrap">
  <div id="query"></div>
  <div id="area"></div>
</div>
</body>
</html>
